import { Dayjs } from "dayjs";
import styles from "../index.module.less";
import { merchantMap } from "../store";
import { GetDaysDiff, GetThisMonthFirstDay } from "./LineChart";
import { deepAddKey } from "@/utils/http";
// 获取指定日期所在月的第一天和最后一天
export function GetMonthStartAndEnd(dateString) {
  const date = dateString ? new Date(dateString) : new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const lastDay = new Date(year, month, 0);
  const formattedFirstDay = `${year}-${month.toString().padStart(2, "0")}-01`;
  const formattedLastDay = `${year}-${month
    .toString()
    .padStart(2, "0")}-${lastDay.getDate()}`;
  return { firstDay: formattedFirstDay, lastDay: formattedLastDay };
}
export const GetTodayDate = () => $dayjs().format("YYYY-MM-DD");
//  获取指定日期的上个月的对应日期
export function GetPreviousMonth(date) {
  const currentDate = new Date(date);
  const lastMonth = new Date(
    currentDate.getFullYear(),
    currentDate.getMonth() - 1,
    currentDate.getDate()
  );
  return $dayjs(lastMonth).format("YYYY-MM-DD");
}
//  获取指定日期的下个月的对应日期
export function GetNextMonth(date) {
  const currentDate = new Date(date);
  const lastMonth = new Date(
    currentDate.getFullYear(),
    currentDate.getMonth() + 1,
    currentDate.getDate() + 1
  );
  return $dayjs(lastMonth).format("YYYY-MM-DD");
}
export default defineComponent({
  setup(props, { expose }) {
    const queryParams = reactive<any>({
      merchant_user_id: "",
      rangeDate: [
        $dayjs(getTimeByZone(new Date(GetThisMonthFirstDay()))),
        $dayjs(getTimeByZone(new Date())),
      ],
    });
    const timeMap = reactive(
      deepAddKey([
        {
          label: $t("dict44"),
          value: "month",
        },
        {
          label: $t("dict45"),
          value: "day",
        },
        {
          label: $t("dict46"),
          value: "week",
        },
      ])
    );
    const current_time = ref("month");
    const header = ref(selectDictLabel(timeMap, current_time.value));
    const tableData = ref([]);
    let defineTable: any = {
      pagination: false,
      bordered: true,
      loading: ref(false),
      dataSource: tableData,
      columns: reactive(
        defineColumns([
          {
            title: $t("table73"),
            dataIndex: "date",
            key: "date",
          },
          {
            title: $t("table74"),
            dataIndex: "new_user_num",
            key: "new_user_num",
          },
          {
            title: `1${header.value}${$t("dict48")}`,
            dataIndex: "one",
            key: "one",
          },
          {
            title: computed(() => `2${header.value}${$t("dict48")}`),
            dataIndex: "two",
            key: "two",
          },
          {
            title: computed(() => `3${header.value}${$t("dict48")}`),
            dataIndex: "three",
            key: "three",
          },
          {
            title: computed(() => `4${header.value}${$t("dict48")}`),
            dataIndex: "four",
            key: "four",
          },
          {
            title: computed(() => `5${header.value}${$t("dict48")}`),
            dataIndex: "five",
            key: "five",
          },
          {
            title: computed(() => `6${header.value}${$t("dict48")}`),
            dataIndex: "six",
            key: "six",
          },
          {
            title: computed(() => `7${header.value}${$t("dict48")}`),
            dataIndex: "seven",
            key: "seven",
          },
          {
            title: computed(() => `8${header.value}${$t("dict48")}`),
            dataIndex: "eight",
            key: "eight",
          },
          {
            title: computed(() => `9${header.value}${$t("dict48")}`),
            dataIndex: "nine",
            key: "nine",
          },
        ])
      ),
    };
    const fetchData = async () => {
      const res: any = await overviewApi.queryRetainData({
        merchant_user_id:
          queryParams.merchant_user_id === ""
            ? undefined
            : queryParams.merchant_user_id,
        start_date: queryParams.rangeDate[0]?.format("YYYY-MM-DD"),
        end_date: queryParams.rangeDate[1]?.format("YYYY-MM-DD"),
        mwd: current_time.value,
      });
      if (res.code != 200) return message.error(res.message);
      tableData.value = res.data.list;
    };
    const initPage = () => fetchData();
    expose({ initPage });
    return () => (
      <div class={styles.Table}>
        <div class={styles.search}>
          <div class={styles.left}>
            <div class={styles.flex_item}>
              <div class={styles.title}>{$t("table14")}</div>
              <div>
                <a-select
                  v-model:value={queryParams.merchant_user_id}
                  onChange={(value) => fetchData()}
                  style="width: 150px"
                  placeholder={$t("placeholder24")}
                  options={merchantMap}
                />
              </div>
            </div>
            <div class={styles.flex_item}>
              <div class={styles.title}>{$t("table73")}：</div>
              <div>
                <a-range-picker
                  v-model:value={queryParams.rangeDate}
                  allowClear={false}
                  onChange={(date: Dayjs, dateString: string) => {
                    const startDateString = dateString[0];
                    const endDateString = dateString[1];
                    const result = GetDaysDiff(startDateString, endDateString);
                    if (result >= 31) {
                      queryParams.rangeDate = [];
                      return message.warn(
                        `${$t("overview64")}30${$t("overview66")}`
                      );
                    }
                    initPage();
                  }}
                  format="YYYY-MM-DD"
                />
              </div>
            </div>
          </div>

          <div class={styles.right}>
            {timeMap.map((item) => (
              <a-button
                type="default"
                size="middle"
                key={item.diff_key}
                disabled={item.value != "month"}
                class={current_time.value === item.value ? styles.active : ""}
                onClick={() => {
                  current_time.value = item.value;
                  header.value = selectDictLabel(timeMap, current_time.value);
                  fetchData();
                }}
              >
                {item.label}
              </a-button>
            ))}
          </div>
        </div>
        <s-table {...defineTable} />
      </div>
    );
  },
});
